package com.example.personblog.utils;

import com.example.personblog.repository.CommentRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;

@Slf4j
@Component
@EnableScheduling
public class LikeTaskUtil {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private CommentRepository commentRepository;

    private static final String COMMENT_LIKE_KEY = "comment:like:";

    /**
     * 每5分钟同步评论点赞数据到数据库
     */
    @Scheduled(fixedRate = 300000)
    @Transactional(rollbackFor = Exception.class)
    public void syncCommentLikesToDB() {
        log.info("开始同步评论点赞数据到数据库...");
        try {
            Set<String> keys = redisTemplate.keys(COMMENT_LIKE_KEY + "*");
            if (keys != null) {
                for (String key : keys) {
                    String commentId = key.substring(COMMENT_LIKE_KEY.length());
                    Long likeCount = redisTemplate.opsForSet().size(key);
                    if (likeCount != null) {
                        commentRepository.updateLikeCount(Long.valueOf(commentId), likeCount);
                    }
                }
            }
            log.info("同步评论点赞数据完成");
        } catch (Exception e) {
            log.error("同步评论点赞数据失败", e);
            throw e;
        }
    }
} 